package com.yinxing.webapi.code.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yinxing.framework.mybatis.TemplateService;
import com.yinxing.webapi.code.entity.sys.SysLog;
import com.yinxing.webapi.code.entity.sys.SysLogDetail;
import com.yinxing.webapi.code.mapper.sys.SysLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

@Slf4j
@Service
@Transactional
public class ISysLogService extends TemplateService<SysLog> {

    private SysLogMapper getMapper() {
        return (SysLogMapper) baseMapper;
    }

    @Async("logExecutor")
    public void asyncInsert(SysLog sysLog) {
        try {
            log.debug(sysLog.toString());
            super.insert(sysLog);
        } catch (Exception e) {
            log.error("记录日志出现错误", e);
        }
    }

    /**
     * 分页查询(不查询ReturnValue_字段，太大了不适合在列表显示)
     * @param page 分页参数
     * @param queryWrapper 查询条件
     */
    public IPage<SysLog> selectMyPage(IPage<SysLog> page, QueryWrapper<SysLog> queryWrapper) {
        return getMapper().selectMyPage(page, queryWrapper);
    }

    /**
     * 根据ID查询(对属性进行了显示调整)
     * @param id PK(主键)
     */
    public SysLogDetail selectDetailById(Long id) throws Exception {
        SysLog sysLog = super.selectById(id);
        SysLogDetail sysLogDetail = new SysLogDetail();
        BeanUtils.copyProperties(sysLogDetail, sysLog);
        //显示处理
        if(sysLog.getException_() != null && sysLog.getException_()) {
            sysLogDetail.setExceptionStr_("是");
        } else {
            sysLogDetail.setExceptionStr_("否");
        }
        //毫秒转秒 保留2位小数
        sysLogDetail.setRunTimeStr_(String.format("%.2f秒", (sysLog.getRunTime_() / 1000f)));
        return sysLogDetail;
    }

    /**
     * 删除历史数据
     * @param days 删除多少天之前的历史数据
     */
    public int deleteHistoryData(int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        //当前日期 - days
        cal.add(Calendar.DAY_OF_MONTH, -days);
        Date deleteDate = cal.getTime();
        QueryWrapper<SysLog> qw = new QueryWrapper<>();
        //<=deleteDate的数据全部删除
        qw.le("LogTime_", deleteDate);
        return super.delete(qw);
    }
}